package com.example.glgk.serviceImpl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.glgk.dto.supportFile.SupportMaterialFileDto;
import com.example.glgk.entity.SupportMaterialFile;
import com.example.glgk.entity.report.AttachmentEntity;
import com.example.glgk.mapper.ReportMapper;
import com.example.glgk.mapper.SupportFileMapper;
import com.example.glgk.service.supportFile.ISupportFileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.*;


@Slf4j
@Service
public class SupportFileServiceImpl extends ServiceImpl<SupportFileMapper, SupportMaterialFile> implements ISupportFileService {


    @Autowired
    private SupportFileMapper supportFileMapper;

    @Autowired
    private ReportMapper reportMapper;

    @Value("${upload.additionalPath}")
    private String uploadPath;


    @Override
    public List<SupportMaterialFileDto> searchSupportFile(String dept,String taskId) {
        List<SupportMaterialFileDto> list=supportFileMapper.searchSupportFile(dept,taskId);
        return list;
    }

    @Override
    @Transactional
    public String upload(MultipartFile[] files, String dept, Integer supportId,Integer fileId,String taskId) throws Exception {
        if (files == null || files.length == 0) {
            return "文件不能为空！";
        }
        //String attachmentId = UUID.randomUUID().toString();
        String absolutePath = Paths.get("").toAbsolutePath().toString(); // 获取当前工作目录的绝对路径
        List<String> fileNameList = new ArrayList<>();
        for (MultipartFile file : files) {

            String name = file.getOriginalFilename();
            try {
                //先创建上传文件的文件夹，不存在才创建
                Path folderPath=Paths.get(absolutePath,uploadPath);
                if (!Files.exists(folderPath)) {
                     Files.createDirectories(folderPath);
                }
            } catch (IOException e) {
                //提示文件已存在
                throw new Exception("文件夹创建失败!");
            }

            try{
                Path path = Paths.get(absolutePath,uploadPath, name);
                Files.copy(file.getInputStream(), path);
            }catch (FileAlreadyExistsException e){
                throw new Exception("文件名重复!");
            }

            assert name != null;
            //String[] split = name.split("\\.");

            fileNameList.add(name);
            //long size = file.getSize();
        }

        String fileNames = String.join(",", fileNameList);

        SupportMaterialFile supportMaterialFile=null;
        if(!StringUtils.isEmpty(fileId)){
            supportMaterialFile=supportFileMapper.selectById(fileId);
        }

        //判断当前是否存在已经上传的文件记录，有则更新，无则插入
        if(!StringUtils.isEmpty(supportMaterialFile)){
            String newFileNames=supportMaterialFile.getFileName()+","+fileNames;
            supportMaterialFile.setFileName(newFileNames);
            supportMaterialFile.setUpdateUser(dept);
            supportMaterialFile.setUpdateTime(new Date());
            supportFileMapper.updateById(supportMaterialFile);

        }else{
            supportMaterialFile=SupportMaterialFile.builder()
                    .fileName(fileNames)
                    .fileAddress(uploadPath)
                    .supportStatus(1)
                    .supportItemId(supportId)
                    .taskId(taskId)
                    .createUser(dept)
                    .createTime(new Date())
                    .build();

            supportFileMapper.insert(supportMaterialFile);
        }
        return fileNames;
    }

    @Override
    @Transactional
    public String deleteFile(Integer fileId,String path,String[] fileNames) {
        supportFileMapper.deleteById(fileId);
        deleteFiles(path,fileNames);
        return "OK";
    }

    @Override
    public List<Map<String, String>> queryAdditionalFile(String dept, String taskId,String indexId) {

        return supportFileMapper.queryAdditionalFile(dept, taskId, indexId);
    }

    @Override
    @Transactional
    public String uploadAdditionalFile(MultipartFile[] files, String dept, String indexId, String fileId,String taskId) throws Exception {

        if (files == null || files.length == 0) {
            return "文件不能为空！";
        }
        String attachmentId = UUID.randomUUID().toString();
        String absolutePath = Paths.get("").toAbsolutePath().toString(); // 获取当前工作目录的绝对路径
        List<String> fileNameList = new ArrayList<>();
        for (MultipartFile file : files) {

            String name = file.getOriginalFilename();
            try {
                //先创建上传文件的文件夹，不存在才创建
                Path folderPath=Paths.get(absolutePath,uploadPath);
                if (!Files.exists(folderPath)) {
                    Files.createDirectories(folderPath);
                }
            } catch (IOException e) {
                //提示文件已存在
                throw new Exception("文件夹创建失败!");
            }

            try{
                Path path = Paths.get(absolutePath,uploadPath, name);
                Files.copy(file.getInputStream(), path);
            }catch (FileAlreadyExistsException e){
                throw new Exception("文件名重复!");
            }

            assert name != null;
            //String[] split = name.split("\\.");

            fileNameList.add(name);
        }

        String fileNames = String.join(",", fileNameList);

        AttachmentEntity attachmentEntity=null;
        if(!StringUtils.isEmpty(fileId)){
            attachmentEntity=reportMapper.queryAttachmentsEntity(fileId);
        }
        //不为空则更新，为空则插入
        if(!StringUtils.isEmpty(attachmentEntity)){
            String curFileName=attachmentEntity.getName();
            String newFileName=curFileName+","+fileNames;
            reportMapper.updateAttachmentsEntity(fileId,newFileName);
        }else{
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            attachmentEntity = AttachmentEntity.builder()
                    .attachmentId(attachmentId) //FJWYBS 附件唯一标识
                    .path(uploadPath) //CCLJ 路径
                    .createUser(dept) //CJR 创建人
                    .dept(dept) //BM  部门
                    .createTime(new Date()) //CJSJ  创建时间
                    .maintainTime(new Date())  //维护时间
                    .name(fileNames) //FJMC  附件名称
                    .indicator(indexId)//  考核指标
                    .taskId(taskId)  //任务Id
                    .build();
            reportMapper.uploadAdditionalFile(attachmentEntity);
        }

        return fileNames;
    }

    @Override
    @Transactional
    public String deleteAdditionalFile(String fileId,String path,String[] fileNames) {
        supportFileMapper.deleteAdditionalFile(fileId);
        deleteFiles(path,fileNames);
        return "OK";
    }

    @Override
    public String deleteFiles(String path,String[] fileNames) {
        String absolutePath = Paths.get("").toAbsolutePath().toString(); // 获取当前工作目录的绝对路径
        for(String name:fileNames){
            Path filePath = Paths.get(absolutePath,uploadPath, name);
            // 创建文件对象
            File file = new File(filePath.toString());
            // 检查文件是否存在
            if (file.exists()) {
                // 尝试删除文件
                if (file.delete()) {
                    System.out.println("文件已成功删除！");
                } else {
                    System.out.println("文件删除失败！");
                }
            } else {
                System.out.println("文件不存在！");
            }
        }
        return "success";
    }


}